#pragma once 

#include <iostream>
#include <memory>
#include <unordered_map>
#include "Epoller.hpp"
#include "Connection.hpp"
#include "Log.hpp"

using namespace EpollModule;

using connection_t = std::shared_ptr<Connection>;

// 只负责管理connection
class Reactor
{
    static const int event_num = 64;
private:
    bool IsConnectionExists(int sockfd)
    {
        return _connections.find(sockfd) != _connections.end();
    }
public:
    Reactor()
        : _isrunning(false)
        , _epoller(std::make_shared<Epoller>())
    {
        _epoller->Init();
    }

    void InsertConnection(const connection_t& conn)
    {
        auto iter = _connections.find(conn->Sockfd());
        if (iter == _connections.end())
        {
            // 1.把链接放到unordered_map中管理
            _connections[conn->Sockfd()] = conn;
            // 2.把新插入进来的链接，写入到内核中
            _epoller->Add(conn->Sockfd(), conn->GetEvents());
            // 3.设置关联关系，让connection回指当前对象
            conn->SetOwner(this);
            LOG(LogLevel::DEBUG) << "add connection success: " << conn->Sockfd();
        }
    }

    void DelConnection(int sockfd)
    {
        if (IsConnectionExists(sockfd))
        {
            // 1.从内核中移除对sockfd的关心
            _epoller->Delete(sockfd);
            // 2.关闭sockfd
            _connections[sockfd]->Close();
            // 3.从_connections中移除对应的连接
            _connections.erase(sockfd);
        }
    }

    void EnableReadWrite(int sockfd, bool readable, bool writeable)
    {
        if (IsConnectionExists(sockfd))
        {
            uint32_t events = (readable?EPOLLIN:0) | (writeable?EPOLLOUT:0) | EPOLLET;
            _connections[sockfd]->SetEvents(events);
            _epoller->Update(sockfd, _connections[sockfd]->GetEvents());
        }
    }

    // 基于事件驱动的事件派发器
    void Dispatcher(int n)
    {
        for (int i = 0; i < n; i++)
        {
            // 对已经就绪的fd派发，派发给指定的模块
            int sockfd = _revs[i].data.fd;
            uint32_t revents = _revs[i].events;

            if ((revents & EPOLLERR) || (revents & EPOLLHUP)) // 错误或挂断
                revents = (EPOLLIN | EPOLLOUT); // 异常事件转化为读写事件
            if ((revents & EPOLLIN) && IsConnectionExists(sockfd))
            {
                _connections[sockfd]->Recver();
            }
            if ((revents & EPOLLOUT) && IsConnectionExists(sockfd))
            {
                _connections[sockfd]->Sender();
            }
        }
    }

    void LoopOnce(int timeout)
    {
        int n = _epoller->Wait(_revs, event_num, timeout);
        Dispatcher(n);
    }

    void DebugPrint()
    {
        std::cout << "Epoller 管理的fd: ";
        for (auto &iter : _connections)
        {
            std::cout << iter.first << " ";
        }
        std::cout << std::endl;
    }

    void Loop()
    {
        _isrunning = true;
        int timeout = -1;
        while (_isrunning)
        {
            LoopOnce(timeout);
            DebugPrint();
        }
        _isrunning = false;
    }

    void Stop() { _isrunning = false; }

    ~Reactor()
    {}
private:
    std::shared_ptr<Epoller> _epoller;
    std::unordered_map<int, connection_t> _connections; // 服务器内部所有的链接
    bool _isrunning;
    struct epoll_event _revs[event_num];
};